﻿@model throneOfGames.Models.Player
<script>
    $(function ()
    {
        //Variables used by the game declared at the start
        var playerSymbol = ' ';
        var opponentSymbol = ' ';
        var group = "@Model.gameID";
        var hub = $.connection.gameHub;
        var painted;
        var content;
        var winningCombinations;
        var turn = "false";
        var squaresFilled = 0;
        var active = true;

        /*Check to see if the current user is the host of the game, the host always gets to start.
        and gets the symbol of X*/
        @if(Model.isHost == true)
        {
            <text>
            playerSymbol = 'X';
            opponentSymbol = 'O';
            </text>
        }
        else
        {
            <text>
                playerSymbol = 'O';
                opponentSymbol = 'X';
            </text>
        }
        //As soon as the window has loaded, we create 2 arrays.
        //One to track each window of x's and o's and one that holds if the td has been filled or not.
        window.onload = function ()
        {
            painted = new Array();
            content = new Array();
            //Hard coded winning combinations that we will use later to determine the winner.
            winningCombinations = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]];

            for (var i = 0; i <= 8; i++)
            {
                painted[i] = false;
                content[i] = '';
            }
        }

        //SignalR, when we receive a call from the other user that he has clicked and made his move, we change our values.
        hub.client.cellClicked = function (cellId)
        {
            $("#" + cellId).text(opponentSymbol);
            content[cellId - 1] = opponentSymbol;
            painted[cellId - 1] = true;
            squaresFilled++;
        }

        //SignalR, here we add to the log at the bottom of the page, that tells us how the game is progressing.
        hub.client.addNewMessageToPage = function (name, message)
        {
            // Add the message to the page. 
            $('#gameLog').append('<li><strong>' + name + '</strong> ' + message + '</li>');
            $('#gameLog').stop().animate({ scrollTop: $("#gameLog")[0].scrollHeight }, 800);
            //We check for winners here incase our opponent has won
            checkForWinners(opponentSymbol);
        };

        //SignalR connection starts
        $.connection.hub.start().done(function ()
        {
            //We connect to the group that is related to the game ID that we are playing in
            hub.server.join(group);
            //Call the function isItMyTurn() that determines if it is the user's turn
            var results = hub.server.isItMyTurn(group, "@User.Identity.Name").done(function (result)
            {
                //Turn becomes true or false, depending on the outcome of isItMyTurn
                turn = result;
            });
            //When we click one of the 9 windows in the board, we execute a function
            $("#tictactoe tr td").click(function ()
            {
                //I declare a new variable to carry the "this" call in the click function,
                //which changes when we enter the next function, within the previous function.
                var $this = this;
                //Check again if it's our turn
                hub.server.isItMyTurn(group, "@User.Identity.Name").done(function (result)
                {
                    turn = result;
                    //If it's our turn, we make our move
                    if (turn == "true")
                    {
                        //We check if we've already checked into the window we're clicking on
                        //If we haven't we go on
                        if (painted[$this.id - 1] == false)
                        {
                            //We send to the other client, which window we clicked on
                            hub.server.clickCell(group, $this.id);
                            //We also send a chat log to the other client, notifying him exactly what we did
                            hub.server.send((group), ("@User.Identity.Name"), ("put " + playerSymbol + " at location " + $this.id));
                            //We no append into our own log what we just did
                            $('#gameLog').append('<li><strong>' + "@User.Identity.Name" + '</strong> ' + ' put ' + playerSymbol + ' at location ' + $this.id + '</li>');
                            //Jquery animation that makes sure that we don't overflow the log
                            $('#gameLog').stop().animate({ scrollTop: $("#gameLog")[0].scrollHeight }, 800);
                            //We enter our symbol into the box we just clicked
                            $($this).text(playerSymbol);
                            //The array content also gets our symbol, to check for winners later
                            content[$this.id - 1] = playerSymbol;
                            //We make sure that we can't make a move until the database tells us it's our turn again
                            turn = "false";
                            //Another array check to make sure we can't check into the same box twice
                            painted[$this.id - 1] = true;
                            //A variable that keeps track of all squares filled, to check if the game ends in a draw.
                            squaresFilled++;
                            //At the end of our turn, we check if we have won
                            checkForWinners(playerSymbol);
                            //If no winner yet, we update the turn and give it over to the next player
                            hub.server.updateTurn(group);
                        }
                    }
                });       
            });
        });
        /*A function that checks for symbols in each location of the array, if the same symbol
        comes up in all 3 locations, in combination with the winning combination, we have a winner*/
        function checkForWinners(symbol)
        {
            for (var a = 0; a < winningCombinations.length; a++)
            {
                if (content[winningCombinations[a][0]] == symbol && content[winningCombinations[a][1]] == symbol &&
                    content[winningCombinations[a][2]] == symbol)
                {
                    active = false;
                    //If our symbol is the winner, we send the other user that we have won.
                    if (playerSymbol == symbol)
                    {
                        hub.server.send((group), ("@User.Identity.Name"), ("won!!"));
                        //And we also append for our own log
                        $('#gameLog').append('<li><strong>' + "You win!" + '</strong>');
                    }
                    //Here we make sure that the game can't go on when a winner has been declared
                    for (var i = 0; i <= 8; i++)
                    {
                        painted[i] = true;
                    }
                    a = winningCombinations.length;
                }
            }
            /*If all squares are filled, and a winner has not been declared, through the active bool variable
            we come to the conclusion that the game was a draw.*/
            if (squaresFilled == 9 && active == true)
            {
                active = false;
                $('#gameLog').append('The game was a draw.');
            }     
        }
    });
</script>
